#include "DBConnection.h"

namespace SQLDoc
{
	DBConnection::DBConnection(void) 
		: DBObject(DBObject::DBOTYPE_CONNECTION)
		,m_databases(QList<DBDatabase*>())
		,m_isValid(false)
		,m_activeDatabase(NULL)
	{ }

	DBConnection::~DBConnection(void)
	{
		// If temporary data were not rewrited to m_childItems
		if (m_databases.count() > 0)
			qDeleteAll(m_databases);
	}

	QString DBConnection::connectionName(void) const
	{ 
		return m_connectionName;
	}

	void DBConnection::setConnectionName(QString val) 
	{
		m_connectionName = val; 
	}

	int DBConnection::selectDatabases(bool refresh /*= false*/)
	{
		if (refresh)
		{
			qDeleteAll(m_databases);
			m_isValid = false;
		}

		if (m_databases.count() == 0 && !m_isValid)
		{
			fillDatabases();
		}

		return m_databases.count();
	}

	int DBConnection::databaseCount(void)
	{
		int count = -1;

		if (m_isValid)
		{
			count = m_databases.count();
			if (!count)
				count = m_childItems.count();

			return count;
		}
		
		return selectDatabases();
	}

	void DBConnection::setActiveDatabase(DBDatabase* activeDb)
	{
		if (m_activeDatabase)
			m_activeDatabase->deactivate();

		m_activeDatabase = activeDb;
	}

	void DBConnection::rewriteDatabases(void)
	{
		int count = m_databases.count();

		while (m_databases.count() > 0)
		{
			addChild(m_databases.at(0));
			m_databases.removeAt(0);
		}
	}
}
